<template>
  <div class="page-container"  v-loading="fullLoading"
  element-loading-text="上传中，请稍候…"
  element-loading-background="rgba(0, 0, 0, 0.5)">
  <div
      style="
        display: flex;
        justify-content: center;
        align-items: center;
      
        width: 80%;
        gap: 40px;
      "
    >
      <el-card class="report-card-left">
        <div class="describe-header"></div>
        <div class="describe-body">
          <h3>分析报告平台上传规则说明</h3>
          <p>一、上传资格要求</p>
          <p>1. 注册用户需完成实名认证</p>
          <p>2. 上传者需具备相关行业从业经验或研究背景</p>
          <p>3. 接受平台内容审核机制</p>

          <p>二、报告内容规范</p>
          <p>
            1. 原创性要求 必须为100%原创内容 允许引用公开数据但需注明来源
            抄袭内容将被下架并可能面临处罚
          </p>
          <p>
            2. 质量标准 报告字数不少于5000字 包含详细的数据分析和行业洞察
            需有清晰的目录和结构 建议包含图表、案例等可视化内容
          </p>
          <p>
            3.格式要求 作者/机构名称 报告名称 内容简介 仅接受PDF格式
            文件大小不超过50MB 文件名格式：行业_报告名称_版本日期
          </p>
          <p>三、定价规则</p>
          <p>1. 基础定价范围：19-999999元/份</p>
          <p>2. 平台收取20%销售分成</p>
          <p>3. 可设置限时折扣(不低于定价的70%)</p>
          <p>4. 优质报告可申请进入平台推荐位(额外10%分成)</p>

          <p>四、上传流程</p>
          <p>1. 登录账号进入"上传报告"页面</p>
          <p>2. 填写报告元数据(标题、摘要、关键词等)</p>
          <p>3. 上传报告文件及封面图</p>
          <p>4. 设置价格和销售权限</p>
          <p>5. 提交审核(1-3个工作日内完成)</p>

          <p>五、销售与结算</p>
          <p>1. 报告售出后款项按月结算</p>
          <p>2. 最低提现金额为10元</p>
          <p>3. 提供销售数据统计分析</p>
          <p>4. 买家评价将影响报告搜索排名</p>

          <p>六、违规处理</p>
          <p>1. 虚假内容：立即下架并扣除当月收入</p>
          <p>2. 版权纠纷：暂停账户直至争议解决</p>
          <p>3. 恶意刷单：取消异常订单并警告</p>

          <p>七、其他说明</p>
          <p>1. 平台有权对报告进行必要的格式调整</p>
          <p>2. 优秀作者可申请成为签约分析师</p>
          <p>3. 定期举办"优质报告评选"活动</p>
        </div>
      </el-card>
      <el-card class="report-card-right">
        <div class="dialog-body">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
            class="report-form"
          >
            <!-- 上传 PDF -->
            <el-form-item label="上传报告" prop="report">
              <div class="upload-container">
                <el-upload
                  ref="uploadRef"
                  class="upload-demo"
                  :action="''"
                  :auto-upload="false"
                  accept=".pdf"
                  :before-upload="beforeUpload"
                  @change="handleFileChange"
                  @remove="handleRemove"
                  :file-list="fileList"
                  :multiple="false"
                >
                  <template #trigger>
                    <el-button type="primary" class="upload-btn"
                      >选择PDF文件</el-button
                    >
                  </template>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 标题 -->
            <el-form-item label="编辑标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入报告标题" />
            </el-form-item>

            <!-- 描述 -->
            <el-form-item label="描述内容" prop="script">
              <el-input
                v-model="form.script"
                type="textarea"
                placeholder="描述"
                :rows="2"
              />
            </el-form-item>

            <!-- 机构名称 -->
            <el-form-item label="机构名称" prop="org">
              <el-input v-model="form.org" placeholder="请输入机构名称" />
            </el-form-item>

            <!-- 作者 -->
            <el-form-item label="作者姓名" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者姓名" />
            </el-form-item>

            <!-- 发布日期 -->
            <el-form-item label="发布日期" prop="publishTime">
              <el-date-picker
                v-model="form.publishTime"
                type="date"
                placeholder="请选择发布日期"
                format="YYYYMMDD"
                value-format="YYYYMMDD"
                style="width: 250px"
              />
            </el-form-item>

            <!-- 报告价格 -->
            <el-form-item label="报告价格" prop="price">
              <el-input
                v-model="form.price"
                placeholder="请输入报告价格"
                style="width: 250px"
              />
            </el-form-item>

            <!-- 报告行业 -->
            <el-form-item label="报告行业" prop="industry">
              <el-cascader
                v-model="form.industry"
                :options="industryOptionsList"
                placeholder="请选择行业"
                clearable
                style="width: 250px"
              />
            </el-form-item>

            <!-- 选择封面 -->
            <el-form-item label="选择封面" prop="coverPic">
              <div class="cover-grid">
                <div
                  v-for="cover in coverList"
                  :key="cover.code"
                  class="cover-item"
                  :class="{ selected: form.coverPic === cover.code }"
                  @click="form.coverPic = cover.code"
                >
                  <img :src="cover.label" alt="封面" />
                </div>
              </div>
            </el-form-item>
          </el-form>

          <div class="button-group">
           
            <el-button @click="resetForm">取消</el-button>
            <template v-if="isLoggedIn">
  <el-button type="primary" :loading="loading" @click="submitForm">
    确认上传
  </el-button>
</template>
<template v-else>
  <el-button type="warning" @click="goLogin">
    请先登录
  </el-button>
</template>
          </div>
        </div>
      </el-card>
    </div>
  
  </div>


 
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { upload } from '../api/upload'
import describe from './components/describe.vue';
import { useRouter } from 'vue-router'
const router = useRouter()
const isLoggedIn = ref(!!localStorage.getItem('token'))

const goLogin=()=> {
  router.push({ name: 'login' })
}


// 表单引用
const formRef = ref(null)
const uploadRef = ref(null)

// 状态
const loading = ref(false)
const showRuleDialog = ref(false)
// 表单模型
const form = reactive({
  report: null,
  title: '',
  script: '',
  org: '',
  author: '',
  publishTime: '',
  price: '',
  industry: [],
  coverPic: ''
})

// 校验规则
const rules = {
  report: [{ required: true, message: '请上传 PDF 文件', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' ,min: 6, max: 32, message: '标题长度在 6 到 32 个字符之间'}],
  script: [{ required: true, message: '请输入描述', trigger: 'blur',min: 16, max: 128, message: '描述长度在 16 到 128 个字符之间' }],
  org: [{ required: true, message: '请输入机构名称', trigger: 'blur',min: 2, max: 16, message: '机构名称长度在 2 到 16 个字符之间' }],
  author: [{ required: true, message: '请输入作者姓名', trigger: 'blur' ,min: 2, max: 16, message: '作者名称长度在 2 到 16 个字符之间'}],
  publishTime: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
  price: [{ required: true, message: '请输入报告价格', trigger: 'blur' }],
  industry: [{ required: true, message: '请选择行业', trigger: 'change' }],
  coverPic: [{ required: true, message: '请选择封面', trigger: 'change' }]
}

// 文件列表
const fileList = ref([])

// 获取封面和行业
const coverList = ref([])
const industryOptionsList = ref([])

const handleUploadData = async () => {
  const cov = await upload.getCover()
  coverList.value = Object.values(cov.data.coverPic)
  const ind = await upload.getIndustry()
  industryOptionsList.value = Object.values(ind.data.industry).map(item => ({
    value: item.code,
    label: item.label,
    children: item.children
      ? Object.values(item.children).map(c => ({ value: c.code, label: c.label }))
      : []
  }))
}

// 上传前校验
const beforeUpload = file => {
 
  const isPdf = file.type === 'application/pdf'
  if (!isPdf) ElMessage.error('仅支持 PDF 格式')
  return isPdf
}



// 选择文件
const handleFileChange = (file, fileListFromEvt) => {
  console.log(file,fileListFromEvt)
  // 先清空之前的文件
  fileList.value = []
  form.report = null

  // 再只取最新的那个 PDF
  const pdfs = fileListFromEvt.filter(f => f.raw && f.raw.type === 'application/pdf')
  if (pdfs.length) {
    // 只保留最后一个
    const last = pdfs[pdfs.length - 1]
    fileList.value = [ last ]
    form.report = last.raw
  }
}

// 移除文件
const handleRemove = (file, lst) => {
  // lst 是 el-upload 当前的 fileList
  fileList.value = lst.filter(f => f.raw && f.raw.type === 'application/pdf')
  form.report = null
}

// 重置表单
function resetForm() {
  formRef.value.resetFields()
  fileList.value = []
}
const fullLoading = ref(false)
// 提交表单
async function submitForm() {
  formRef.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    fullLoading.value = true 
    try {
      const formData = new FormData()
      formData.append('report', form.report)
      Object.entries(form).forEach(([key, val]) => {
        if (key === 'report') return
        if (Array.isArray(val)) formData.append(key, val[val.length - 1])
        else formData.append(key, val)
      })
      const res = await upload.uploadReport(formData)
      if (res.code === 0) {
        ElMessage.success('报告上传成功')
        fileList.value = []
        form.report = null
     
        uploadRef.value.clearFiles()
        // resetForm()
      } else {
        // ElMessage.error(res.msg)
      }

    } catch {

    } finally {
      loading.value = false
      fullLoading.value = false
    }
  })
}

onMounted(() => {

  handleUploadData()
})
</script>

<style lang="scss" scoped>
/* 基础容器优化 */
.page-container {
  min-height: calc(101.3vh - 80px); // 减去顶栏高度
  
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/xwimg/reportBg.png") center/cover no-repeat;

  @media (max-width: 768px) {
    height: auto;
    padding: 20px 10px;
  }
}

/* 双栏布局响应式处理 */
.report-card-left,
.report-card-right {
  width: 50%;
  height: 75vh;
  overflow-y: auto;
  border-radius: 12px;
  background: linear-gradient(135deg, #f5f7fa 0%, #6997e0 100%);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  opacity: 0.9;
  margin: 0 10px;

  @media (max-width: 1200px) {
    width: 45%;
    height: auto;
    min-height: 70vh;
  }

  @media (max-width: 768px) {
    width: 100%;
    height: auto;
    margin: 10px 0;
  }
}

/* 移动端布局调整 */
@media (max-width: 768px) {
  .page-container > div {
    flex-direction: column;
    width: 100%;
    height: auto;
    gap: 20px;
  }
}

/* 左侧说明卡片优化 */
.report-card-left {
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .describe-header {
    width: 100%;
    height: 40px;
    background: url("../assets/xwimg/logo2.png") center/contain no-repeat;
    margin-bottom: 20px;
  }

  .describe-body {
    height: 58%;
    margin-bottom: 10px;
    overflow-y: auto;
    padding-right: 15px;
    font-size: 13px;
    line-height: 1.2;
    // border: 1px solid #fff;

    h3 {
      color: #2c3e50;
      margin-bottom: 20px;
      font-size: 18px;
    }

    p {
      margin: 12px 0;
      color: #34495e;

      &:first-of-type {
        font-weight: 500;
        color: #2c3e50;
      }
    }

    /* 滚动条美化 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 4px;
    }
  }
}

/* 右侧表单卡片优化 */
.report-card-right {
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
      /* 滚动条美化 */
      &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 4px;
    }

  .dialog-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 20px;
    
  
    
  }

  .report-form {
    flex: 1;
    overflow-y: auto;
    padding-right: 15px;

    /* 表单项响应式 */
    :deep(.el-form-item) {
      margin-bottom: 18px;

      @media (max-width: 768px) {
        margin-bottom: 12px;
      }
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #2c3e50;
    }
  }
}

/* 上传区域优化 */
.upload-container {
  .upload-btn {
    width: 160px;
    transition: all 0.3s;

    @media (max-width: 768px) {
      width: 100%;
    }
  }

  :deep(.el-upload-list) {
    margin-top: 8px;
    max-width: 400px;
  }
}

/* 封面选择网格优化 */
.cover-grid {
  display: flex;
  gap: 12px;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));

  .cover-item {
    width: 68px;
    height: 100px;
    display: block;
  
    transition: transform 0.2s ease;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    &:hover {
      transform: translateY(-3px);
    }

    &.selected {
      border: 2px solid #409eff;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }
}

/* 按钮组优化 */
.button-group {
  margin-top: auto;
  padding-top: 20px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;

  @media (max-width: 768px) {
    flex-direction: column-reverse;

    button {
      width: 100%;
    }
  }
}

/* 全局字体优化 */
body {
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial,
    "PingFang SC", "Hiragino Sans GB", STHeiti, "Microsoft YaHei", sans-serif;
}

/* 移动端输入优化 */
@media (max-width: 768px) {
  :deep(.el-input),
  :deep(.el-date-editor),
  :deep(.el-cascader) {
    width: 100% !important;
  }

  .cover-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
/* 去掉 el-link 下划线并改成灰色 */
.rule-link {
  /* 取消下划线 */
  text-decoration: none !important;
  /* 灰色字体 */
  color: #888888 !important;
}

.rule-link:hover {
  /* hover 时稍微加深一点 */
  color: #555555 !important;
  /* 依然不出现下划线 */
  text-decoration: none !important;
}

</style>